package com.xiaochun.hxhj.wxapi;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.WindowManager;

import com.myapp.MyApp;
import com.tencent.mm.sdk.constants.ConstantsAPI;
import com.tencent.mm.sdk.modelbase.BaseReq;
import com.tencent.mm.sdk.modelbase.BaseResp;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.modelmsg.ShowMessageFromWX;
import com.tencent.mm.sdk.modelmsg.WXAppExtendObject;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.util.InfoEventMessage;
import com.util.MyLog;
import com.util.RequestManager;
import com.util.ToastUtils;
import com.xiaochun.hxhj.BandPhoneActivity;
import com.xiaochun.hxhj.MainActivity;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;


public class WXEntryActivity extends Activity implements IWXAPIEventHandler {

    public static final String action = "jason.broadcast.action";
    private MyApp m = null;
    // IWXAPI 是第三方app和微信通信的openapi接口
    private IWXAPI api;
    private String openid;
    private IWXAPI iwxapi;
    private Context context;
    private String openidWX = "";
    private MyApp myApp;
    private JSONObject dataFB;
    private String status = "0";
    private String apptype;
    private String textData;
    private String access_token;
    private String is_login;
    private String headimgurl = "";
    private String is_bind_wx = "";
    private String token = "";
    private String id = "";
    private String username = "";
    private String nickname = "";
    private String mobile = "";
    private String avatar = "";
    private String score = "";
    private String student_id = "";
    private String user_id;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        getSupportActionBar().hide();
        // 隐藏状态栏
        myApp = (MyApp) getApplicationContext();
        context = this;
        SharedPreferences sharedPreferences = getSharedPreferences("userinfo", Context.MODE_MULTI_PROCESS);
        String token = sharedPreferences.getString("token", "");
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        //TODO    weixin_appid
        iwxapi = WXAPIFactory.createWXAPI(this, myApp.getAppId(), false);
        iwxapi.handleIntent(getIntent(), this);

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        api.handleIntent(intent, this);
    }

    // 微信发送请求到第三方应用时，会回调到该方法
    @Override
    public void onReq(BaseReq req) {
        switch (req.getType()) {
            case ConstantsAPI.COMMAND_GETMESSAGE_FROM_WX:
                MyLog.e("微信","111111");
                goToGetMsg();
                break;
            case ConstantsAPI.COMMAND_SHOWMESSAGE_FROM_WX:
                goToShowMsg((ShowMessageFromWX.Req) req);
                MyLog.e("微信","222222");
                break;
            case ConstantsAPI.COMMAND_LAUNCH_BY_WX:
                MyLog.e("微信","3333333");
                ToastUtils.show("111");
                break;
            default:
                break;
        }
    }

    // 第三方应用发送到微信的请求处理后的响应结果，会回调到该方法
    @Override
    public void onResp(BaseResp resp) {
        Log.e("微信", "分享成功   " + resp.toString());
        openid = resp.openId;
        switch (resp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                if (resp.toString().contains("com.tencent.mm.sdk.modelmsg.SendMessageToWX$Resp")) {
                    Log.e("微信", "分享成功");
                    ToastUtils.show("分享成功");
                    EventBus.getDefault().post(new InfoEventMessage("分享得积分"));
                    finish();
                } else {
                    try {
                        SendAuth.Resp newResp = (SendAuth.Resp) resp;
                        String wxcode = newResp.code;
                        Log.e("微信", "登陆成功" + wxcode);
                        getWxOpenId(wxcode);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                if (resp.toString().contains("com.tencent.mm.opensdk.modelmsg.SendMessageToWX$Resp")) {
                    Log.e("微信", "分享取消");
                    ToastUtils.show("分享取消");

                    finish();
                } else {
                    Log.e("微信", "登录取消");
//
                    finish();
                }
                break;
            case BaseResp.ErrCode.ERR_SENT_FAILED:
                if (resp.toString().contains("com.tencent.mm.opensdk.modelmsg.SendMessageToWX$Resp")) {
                    Log.e("微信", "分享失败");
                    ToastUtils.show("分享失败");

                    finish();
                } else {
                    Log.e("微信", "登录失败");
//
                    finish();
                }
                break;
            default:
                break;
        }
    }

    private void goToGetMsg() {
        finish();
    }

    private void goToShowMsg(ShowMessageFromWX.Req showReq) {
        WXMediaMessage wxMsg = showReq.message;
        WXAppExtendObject obj = (WXAppExtendObject) wxMsg.mediaObject;
        StringBuffer msg = new StringBuffer(); // 组织一个待显示的消息内容
        msg.append("description: ");
        msg.append(wxMsg.description);
        msg.append("\n");
        msg.append("extInfo: ");
        msg.append(obj.extInfo);
        msg.append("\n");
        msg.append("filePath: ");
        msg.append(obj.filePath);
        finish();
    }

    /**
     * 获取微信OpenId
     */
    private void getWxOpenId(String code) {
        //TODO  appid   secret   431d2dff909ae0f1
        String url = myApp.getWebConfig()+"/addons/xshop/vendor/login?vendor=App";
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("pid", "0");
        paramsMap.put("code", code);
        paramsMap.put("device_id", myApp.getDeviceId());
        RequestManager.getInstance(context).requestAsyn(url, RequestManager.TYPE_POST_FORM, paramsMap, new RequestManager.ReqCallBack() {



            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("code--result", result.toString());
//                {"code":1,"msg":"发送成功","time":"1571105679","data":8851}
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    JSONObject data = jsonObject.getJSONObject("data");
                    is_bind_wx = data.getString("is_bind_wx");
                    token = data.getString("token");


                    id = data.getString("id");
                    username = data.getString("username");
                    nickname = data.getString("nickname");
                    mobile = data.getString("mobile");
                    avatar = data.getString("avatar");
                    score = data.getString("score");
                    student_id = data.getString("student_id");
                    user_id = data.getString("user_id");

                    msg.arg1 = 2;
                    handler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 1;
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                Log.e("result", errorMsg);
                if (errorMsg.equals("未登录")) {
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handler.sendMessage(msg);
                }
            }
        });

    }

    /**
     * 获取微信用户信息
     */
    private void getWXUserinfo() {
//        https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
        String url = "https://api.weixin.qq.com/sns/userinfo";
        HashMap<String, String> paramsMap = new HashMap<>();
//        paramsMap.put("access_token", access_token);
//        paramsMap.put("openid", openidWX);
        String s = url + "?access_token=" + access_token + "&openid=" + openidWX;
        MyLog.e("微信信息request", s);
        RequestManager.getInstance(context).requestAsyn(s, RequestManager.TYPE_GET, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("微信信息code--result", result.toString());
//                {"code":1,"msg":"发送成功","time":"1571105679","data":8851}
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    headimgurl = jsonObject.getString("headimgurl");
                    msg.arg1 = 4;
                    handler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    headimgurl ="";
                    msg.arg1 = 4;
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                MyLog.e("result", errorMsg);
                headimgurl ="";
                Message msg = new Message();
                msg.arg1 = 4;
                handler.sendMessage(msg);
                /*if (errorMsg.equals("未登录")) {
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handler.sendMessage(msg);
                }*/
            }
        });

    }

    /**
     * 获取微信
     */
    private void getcode(String openid) {

        String url = myApp.getWebConfig() + "/api/user/wxlogin2";
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("openid", openid);
        MyLog.e("微信头像上传",headimgurl+"    微信头像上传");
        paramsMap.put("avatar", headimgurl);
        RequestManager.getInstance(context).requestAsyn(url, RequestManager.TYPE_POST_FORM, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("code--result", result.toString());
//                {"code":1,"msg":"发送成功","time":"1571105679","data":8851}
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.getString("code").equals("0")) {

                        msg.obj = jsonObject.getString("msg");
                        msg.arg1 = 0;
                        handler.sendMessage(msg);
                        return;
                    }
                    dataFB = jsonObject.getJSONObject("data");
                    is_login = dataFB.getString("is_login");

                    is_login = dataFB.getString("is_login");
                    if ("1".equals(is_login)){
                        JSONObject userinfo = dataFB.getJSONObject("userinfo");
                        String id = userinfo.getString("id");
                        String username = userinfo.getString("username");
                        String nickname = userinfo.getString("nickname");
                        String mobile = userinfo.getString("mobile");
                        String avatar = userinfo.getString("avatar");
                        String score = userinfo.getString("score");
                        String token = userinfo.getString("token");
                        String user_id = userinfo.getString("user_id");
                        String is_expert = userinfo.getString("is_expert");
                        String createtime = userinfo.getString("createtime");
                        String expiretime = userinfo.getString("expiretime");
                        String expires_in = userinfo.getString("expires_in");
                        SharedPreferences sharedPreferences = context.getSharedPreferences("userinfo", Activity.MODE_MULTI_PROCESS);
                        sharedPreferences.edit().putString("is_expert", is_expert).commit();
                        sharedPreferences.edit().putString("mobile", mobile).commit();
                        sharedPreferences.edit().putString("username", username).commit();
                        sharedPreferences.edit().putString("avatar", avatar).commit();
                        sharedPreferences.edit().putString("score", score).commit();
                        sharedPreferences.edit().putString("token", token).commit();
                        sharedPreferences.edit().putString("user_id", user_id).commit();
                        sharedPreferences.edit().putString("nickname", nickname).commit();
                    }


                    msg.arg1 = 3;
                    handler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 1;
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                Log.e("result", errorMsg);
                if (errorMsg.equals("未登录")) {
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handler.sendMessage(msg);
                }
            }
        });

    }


    public Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            Intent intent = null;
            super.handleMessage(msg);
            switch (msg.arg1) {
                case 0:
                    String str = (String) msg.obj;
                    ToastUtils.show(str);
                    break;
                case 1:
                    ToastUtils.show("网络错误，请稍后重试");

                    break;
                case 2:
                    if ("0".equals(is_bind_wx)){
                        //未绑定
                        intent = new Intent(context, BandPhoneActivity.class);
                        intent.putExtra("token",token);
                        startActivity(intent);
                        finish();
                    }else if ("1".equals(is_bind_wx)){
                        //已绑定

                        SharedPreferences sharedPreferences = context.getSharedPreferences("userinfo", Context.MODE_MULTI_PROCESS);
//                        String isRestarApp = getUserInfo("isRestarApp");
                        String isRestarApp =  sharedPreferences.getString("isRestarApp","");
                        if ("true".equals(isRestarApp)){
                            intent = new Intent(context, MainActivity.class);
                            startActivity(intent);
                            sharedPreferences.edit().putString("isRestarApp","false");
                        }

                        sharedPreferences.edit().putString("id",id).commit();
                        sharedPreferences.edit().putString("username",username).commit();
                        sharedPreferences.edit().putString("nickname",nickname).commit();
                        sharedPreferences.edit().putString("mobile",mobile).commit();
                        sharedPreferences.edit().putString("avatar",avatar).commit();
                        sharedPreferences.edit().putString("score",score).commit();
                        sharedPreferences.edit().putString("student_id",student_id).commit();
                        sharedPreferences.edit().putString("is_bind_wx",is_bind_wx).commit();
                        sharedPreferences.edit().putString("token",token).commit();
                        sharedPreferences.edit().putString("user_id",user_id).commit();
                        EventBus.getDefault().post(new InfoEventMessage("登录签到"));
                        EventBus.getDefault().post(new InfoEventMessage("登录页面finish"));
                        MyApp.setIsRequest(true);
                        finish();
                    }
//                    getWXUserinfo();


                    break;
                case 3:
                    //TODO  微信登录成功

                    /*if ("1".equals(is_login)){
                        EventBus.getDefault().post(new InfoEventMessage("笔记本刷新"));
                        EventBus.getDefault().post(new InfoEventMessage("登录页面finish"));
                        finish();
                    }else{
                        intent = new Intent(context, BandPhoneActivity.class);
                        intent.putExtra("openid",openidWX);
                        intent.putExtra("access_token",access_token);
                        intent.putExtra("headimgurl",headimgurl);
                        startActivity(intent);
                        finish();
                    }*/


                   /* try {
                        if ("0".equals(status)){
                            intent = new Intent(context, WXEntryActivity.class);
                            intent.putExtra("wxid",openidWX);
                            intent.putExtra("fbid","");
                            intent.putExtra("logintype","wx");
                            startActivity(intent);
                            finish();
                        }else if ("1".equals(status)){
                            JSONObject useri = dataFB.getJSONObject("userinfo");
                            SharedPreferences spuserInfo = getSharedPreferences("userInfo", Activity.MODE_PRIVATE);
                            spuserInfo.edit().putString("username", useri.getString("username")).commit();
                            spuserInfo.edit().putString("nickname", useri.getString("nickname")).commit();
                            spuserInfo.edit().putString("mobile", useri.getString("mobile")).commit();
                            spuserInfo.edit().putString("score", useri.getString("score")).commit();
                            spuserInfo.edit().putString("token", useri.getString("token")).commit();
                            spuserInfo.edit().putString("user_id", useri.getString("user_id")).commit();
                            spuserInfo.edit().putString("level", useri.getString("level")).commit();
                            String language =  PreferenceUtil.getString("language", "");
                            String templanuage = "";
                            if ("0".equals(useri.getString("language"))){
//                        spuserInfo.edit().putString("language", "zh").commit();
                                templanuage = "zh";
                            }else if ("1".equals(useri.getString("language"))){
                                templanuage = "en";
                            }
                            if (!language.equals(templanuage)){
                                PreferenceUtil.commitString("language", language);
                            }
                            intent = new Intent(context, MainActivity.class);
                            startActivity(intent);
                            myApp.destoryActivity("登陆页面");
                            finish();
                        }
                    }catch (Exception e){

                    }*/
                    break;
                case 4:
                    getcode(openidWX);
                    break;
                case 5:


                    break;
            }
        }
    };

}